<template>
  <NModal :show="visible" :title="title" preset="card" class="w-600px" @update:show="emit('update:visible', $event)">
    <NForm ref="formRef" :model="formData" :rules="formRules" label-placement="left" :label-width="100">
      <NFormItem label="父分类" path="parentId">
        <NTreeSelect
          v-model:value="formData.parentId"
          :options="categoryTreeOptions"
          placeholder="请选择父分类（不选则为顶级分类）"
          clearable
          :consistent-menu-width="false"
          :show-path="true"
          :filterable="true"
        />
        <template #feedback>
          <span v-if="categoryTreeOptions.length === 0" class="text-gray-400 text-xs">
            暂无分类，将创建为顶级分类
          </span>
        </template>
      </NFormItem>
      <NFormItem label="分类名称" path="name">
        <NInput v-model:value="formData.name" placeholder="请输入分类名称" />
      </NFormItem>
      <NFormItem label="分类编码" path="code">
        <NInput v-model:value="formData.code" placeholder="请输入分类编码" />
      </NFormItem>
      <NFormItem label="排序" path="sortOrder">
        <NInputNumber v-model:value="formData.sortOrder" placeholder="请输入排序" class="w-full" />
      </NFormItem>
      <NFormItem label="图标" path="icon">
        <NInput v-model:value="formData.icon" placeholder="请输入图标" />
      </NFormItem>
      <NFormItem label="描述" path="description">
        <NInput v-model:value="formData.description" type="textarea" placeholder="请输入描述" :rows="3" />
      </NFormItem>
      <NFormItem label="状态" path="status">
        <NRadioGroup v-model:value="formData.status">
          <NRadio :value="1">启用</NRadio>
          <NRadio :value="0">禁用</NRadio>
        </NRadioGroup>
      </NFormItem>
    </NForm>
    <template #footer>
      <NSpace justify="end">
        <NButton @click="handleClose">取消</NButton>
        <NButton type="primary" @click="handleSubmit">确定</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import type { FormInst, FormRules, TreeSelectOption } from 'naive-ui';
import type { AssetCategory } from '@/service/api/dataplatform/asset';
import { addCategory, updateCategory } from '@/service/api/dataplatform/asset';

interface Props {
  visible: boolean;
  operateType: 'add' | 'edit';
  rowData: AssetCategory | null;
  categoryTree: AssetCategory[];
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:visible': [visible: boolean];
  success: [];
}>();

const formRef = ref<FormInst | null>(null);

const defaultFormData: AssetCategory = {
  parentId: undefined,
  name: '',
  code: '',
  sortOrder: 0,
  icon: '',
  description: '',
  status: 1
};

const formData = ref<AssetCategory>({ ...defaultFormData });

const formRules: FormRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
};

const title = computed(() => (props.operateType === 'add' ? '新增分类' : '编辑分类'));

// 转换分类树为TreeSelect选项
const categoryTreeOptions = computed(() => {
  if (!props.categoryTree || props.categoryTree.length === 0) {
    return [];
  }
  
  // 如果是编辑模式，需要过滤掉当前分类及其子分类，避免循环引用
  let filteredTree = props.categoryTree;
  if (props.operateType === 'edit' && props.rowData?.id) {
    filteredTree = filterCurrentCategory(props.categoryTree, props.rowData.id);
  }
  
  return convertToTreeSelectOptions(filteredTree);
});

// 过滤掉当前分类及其子分类
function filterCurrentCategory(categories: AssetCategory[], currentId: number): AssetCategory[] {
  if (!categories) return [];
  
  return categories
    .filter(category => category.id !== currentId)
    .map(category => ({
      ...category,
      children: category.children ? filterCurrentCategory(category.children, currentId) : undefined
    }));
}

function convertToTreeSelectOptions(categories: AssetCategory[]): TreeSelectOption[] {
  if (!categories) return [];
  return categories.map(category => ({
    label: category.name || '',
    value: category.id!,
    children: category.children && category.children.length > 0 
      ? convertToTreeSelectOptions(category.children) 
      : undefined
  }));
}

watch(
  () => props.visible,
  val => {
    if (val) {
      if (props.operateType === 'edit' && props.rowData) {
        formData.value = { ...props.rowData };
      } else {
        formData.value = { ...defaultFormData };
      }
    }
  }
);

function handleClose() {
  emit('update:visible', false);
}

async function handleSubmit() {
  await formRef.value?.validate();
  try {
    const submitData = { ...formData.value };
    // 如果没有选择父分类，设置为0（顶级分类）
    if (!submitData.parentId) {
      submitData.parentId = 0;
    }
    
    if (props.operateType === 'add') {
      await addCategory(submitData);
      window.$message?.success('新增成功');
    } else {
      await updateCategory(submitData);
      window.$message?.success('更新成功');
    }
    emit('success');
    handleClose();
  } catch (error) {
    window.$message?.error(props.operateType === 'add' ? '新增失败' : '更新失败');
  }
}
</script>
